<?php

function sess_open($save_path,$session_name=SESSIONNAME) {
  $sNewSession='';
  if ( key_exists(SESSIONNAME,$_COOKIE) ) {
    $sNewSession=ereg_replace('[^a-f0-9]','',$_COOKIE[SESSIONNAME]);
    session_id($sNewSession);
  } else {
    $sNewSession=sha1(mt_rand().microtime());
    session_id($sNewSession);
  }
  return true;
}

function sess_close() {
  return true;
}

function sess_read($key) {
  global $oDB;
  $value=$oDB->simple_query("/* sessiondbhandler.php sess_read */ select `value` from ".SESSIONDB.".".SESSIONTABLE." WHERE `sesskey`=?",'s',$key);
  return $value;
}

function sess_write($key,$value) {
  global $oDB;
  $expire=time()+SESS_LIFETIME;
  $ip=$_SERVER['REMOTE_ADDR'];
  $qry="/* sessiondbhandler.php sess_write */ REPLACE INTO ".SESSIONDB.".".SESSIONTABLE." (sesskey,expire,value,ipaddr) VALUES (?,?,?,?)";
  if ( $oDB ) {
    $sNewSession=sha1(mt_rand().microtime());
    $oDB->prepandexec($qry,'siss',array($sNewSession,$expire,$value,$ip));
    setcookie(SESSIONNAME,$sNewSession,0,'/',DOMAIN,FALSE,TRUE);
  } else {
    exit();
  }
  return true;
}

function sess_destroy($key) {
  global $oDB;
  return true;
  $qry="/* sessiondbhandler sess_destroy */ DELETE FROM ".SESSIONDB.".".SESSIONTABLE." WHERE `sesskey`=?";
  $oDB->prepandexec($qry,'s',$key);
  return true;
}
function sess_gc($maxlifetime) {
  global $oDB;
  $qry="/* sessiondbhandler sess_gc */ DELETE FROM ".SESSIONDB.".".SESSIONTABLE." WHERE `expire`<unix_timestamp()";
  $oDB->prepandexec($qry);
  return true;
}

session_set_save_handler(
	"sess_open",
	"sess_close",
	"sess_read",
	"sess_write",
	"sess_destroy",
	"sess_gc");
